<template>
  <AddOrEditDialog
    ref="addOrEditDialogRef"
    title="年级"
    :formHeader="formHeader"
    :form="form"
    :action="action"
    :url="$urls.API_URL_BACKSTAGE_SCHOOLCLASS_MANAGE"
  >
    <template #schoolTeacher>
      <el-autocomplete
        v-model="schoolTeacherState"
        :fetch-suggestions="querySearch"
        placeholder="请输入教师"
        @select="handleSelect"
        clearable
      />
    </template>
    <template #schoolMajor>
      <el-autocomplete
        v-model="schoolMajorState"
        :fetch-suggestions="schoolMajorSearch"
        placeholder="请输入专业"
        @select="schoolMajorHandleSelect"
        clearable
      />
    </template>
    <template #schoolGrade>
      <el-autocomplete
        v-model="schoolGradeStatae"
        :fetch-suggestions="schoolGradeSearch"
        placeholder="请输入专业"
        @select="schoolGradeHandleSelect"
        clearable
      />
    </template>
  </AddOrEditDialog>
</template>

<script lang="ts" setup>
import AddOrEditDialog from '@/components/base/table/form/AddOrEditDialog.vue';
import { Role } from '@/types/interface/auth_interface';
import {
  defineExpose, defineProps, getCurrentInstance, ref, withDefaults,
} from 'vue';
import { FormHeader } from '@/types/interface/base_interface';
import { SchoolGrade, SchoolMajor } from '@/types/interface/school_interface';
import Request from '@/api/request/request';

// 接收父容器参数
interface Props {
  action?: string, // 表单的处理类型，post表示提交，put表示编辑
}
const { proxy } = getCurrentInstance();

const props = withDefaults(defineProps<Props>(), {
  action: 'post',
});

// 表单元素
const formHeader = ref<FormHeader[]>([
  {
    label: '班级名称',
    prop: 'name',
    rules: [
      {
        required: true,
        message: '不能为空',
        trigger: 'blur',
      },
      {
        min: 2,
        max: 10,
        message: '长度在 2 到 10个字符',
        trigger: 'blur',
      },
    ],
  },
  {
    label: '排序',
    prop: 'sort',
    type: 'number',
  },
  {
    label: '专业',
    prop: 'schoolMajor',
    type: 'custom', // 自定义的意思
    rules: [
      {
        required: true,
        message: '不能为空',
        trigger: 'blur',
      },
    ],
  },
  {
    label: '年级',
    prop: 'schoolGrade',
    type: 'custom', // 自定义的意思
    rules: [
      {
        required: true,
        message: '不能为空',
        trigger: 'blur',
      },
    ],
  },
  {
    label: '教师',
    prop: 'schoolTeacher',
    type: 'custom', // 自定义的意思
    rules: [
      {
        required: true,
        message: '不能为空',
        trigger: 'blur',
      },
    ],
  },
]);
interface schoolTeacher {
  id: number
  value: string
}
interface schoolGradeRem {
  id: number
  value: string
}
interface schoolMajor {
  id: number
  value: string
}
// 可以自定义处理方法，也可以使用element-plus定义的方法
const filter = (arr:[]) => {
  let obj:{id:number, value:string};
  let list: any[] = [];
  arr.forEach((item:any) => {
    obj = {
      id: item.id,
      value: item.name,
    };
    list.push(obj);
  });
  return list;
};
const schoolTeacherState = ref();
const schoolMajorState = ref();
const schoolGradeStatae = ref();
// queryString 为在框中输入的值
// callback 回调函数,将处理好的数据推回
// 教师 根据用户输入的字符串去后端查询对应的数据，然后通过自定义的数据处理方法，将数据处理成表单需要的数据，然后cb返回表单，表单才能相对应展示数据
const querySearch = async (queryString: string, cb: any) => {
  let resData:any = await new Request(proxy.$urls.API_URL_BACKSTAGE_SCHOOLTEACHER_MANAGE, null, {
    params: {
      name: queryString,
    },
  }).get();
  if (resData.code === 200) {
    const { data } = resData.data;
    let list = filter(data);
    cb(list);
  }
};
const schoolMajorSearch = async (queryString: string, cb: any) => {
  let resData:any = await new Request(proxy.$urls.API_URL_BACKSTAGE_SCHOOLMAJOR_MANAGE, null, {
    params: {
      name: queryString,
    },
  }).get();
  if (resData.code === 200) {
    const { data } = resData.data;
    let list = filter(data);
    cb(list);
  }
};
const schoolGradeSearch = async (queryString: string, cb: any) => {
  let resData:any = await new Request(proxy.$urls.API_URL_BACKSTAGE_SCHOOLGRADE_MANAGE, null, {
    params: {
      name: queryString,
    },
  }).get();
  if (resData.code === 200) {
    const { data } = resData.data;
    let list = filter(data);
    cb(list);
  }
};
// 表单对象
const form = ref<SchoolGrade>();
// 教师 在点击选中建议，也就是点击从后端获取到的数据后，完成相对应的事件，例如查询某条数据（通常用于修改表单绑定值）
const handleSelect = (item: schoolTeacher) => {
  form.value!.teacherId = item.id; // 将选中的id赋值给要传递后台的form表单
  schoolTeacherState.value = item.value; // 对应修改表单绑定值
};
const schoolMajorHandleSelect = (item: schoolMajor) => {
  form.value!.majorId = item.id; // 将选中的id赋值给要传递后台的form表单
  schoolMajorState.value = item.value; // 对应修改表单绑定值
};
const schoolGradeHandleSelect = (item: schoolGradeRem) => {
  form.value!.gradeId = item.id; // 将选中的id赋值给要传递后台的form表单
  schoolGradeStatae.value = item.value; // 对应修改表单绑定值
};
let formInit:SchoolGrade; // 记录表单第一次传入的值,用于表单重置恢复初始值使用
// 打开对话框，gong供父组件调用，传入表单对象
const addOrEditDialogRef = ref();
const openDialog = (schoolGrade:SchoolGrade, action:string) => {
  formInit = { ...schoolGrade }; // 获取初始值，这里要做深拷贝，避免与form对象引用的地址一致，导致无法恢复初始值
  form.value = { ...schoolGrade };
  console.log(form.value);
  // 解决教师编辑无值
  if (form.value.schoolTeacher && action !== 'put') {
    schoolTeacherState.value = form.value.schoolTeacher.name;
  } else {
    schoolTeacherState.value = '';
  }
  // 解决年级编辑无值
  if (form.value.schoolGrade && action !== 'put') {
    schoolGradeStatae.value = form.value.schoolGrade.name;
  } else {
    schoolGradeStatae.value = '';
  }
  // 解决专业编辑无值
  if (form.value.schoolMajor && action !== 'put') {
    schoolMajorState.value = form.value.schoolMajor.name;
  } else {
    schoolMajorState.value = '';
  }
  addOrEditDialogRef.value!.openDialog();
};
// 提交表单成功后的钩子函数
const afterSubmitSuccess = () => {
  // 让表单恢复为传入对象时的初始值，注意要深度拷贝，避免初始值收到污染
  form.value = { ...formInit };
};
// 暴露组件给父容器使用
defineExpose({
  openDialog,
});
</script>

<style scoped>

</style>
